#pragma once

#include <iostream>
#include <cstdlib>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include "Task.hpp"

using namespace std;

class Channel
{
public:
    Channel(int wfd, pid_t subid)
        :_wfd(wfd), _subid(subid)
    {
        _name = "channel-" + to_string(wfd) + "-" + to_string(subid);
    }

    int fd() { return _wfd; }
    pid_t id() { return _subid; }
    string name() { return _name; }

    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }

    ~Channel(){}
private:
    int _wfd; 
    pid_t _subid;
    string _name;
};

class ChannelManage
{
public:
    ChannelManage() : _next(0) {}

    void InsertChannel(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
    }

    Channel& Select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }

    void PrintChannel()
    {
        for(auto &channel : _channels)
        {
            cout << channel.name() <<endl;
        }
    }

    void CloseAll()
    {
        for(auto &Channel : _channels)
        {
            Channel.Close();
            //cout << "关闭: " << Channel.name() << endl;
        }
    }

    void StopSubProcess()
    {
        for(auto &Channel : _channels)
        {
            Channel.Close();
            cout << "关闭: " << Channel.name() << endl;
        }
    }

    void WaitSubProcess()
    {
        for(auto &Channel : _channels)
        {
            Channel.Wait();
            cout << "回收: " << Channel.name() << endl;
        } 
    }

    void CloseAndWait()
    {
        //每一个子进程的后续子进程的文件描述符表中都它对应的wid,这会导致在
        //顺序关闭子进程时若将Stop与Wait合并时,第一个子进程的管道将无法被
        //关闭,只是引用计数减一而导致read堵塞

        //解决方案一:倒着关闭
        // for(int i = _channels.size() - 1; i>=0; i--)
        // {
        //     _channels[i].Close();
        //     cout << "关闭: " << _channels[i].name() << endl;
        //     _channels[i].Wait();
        //     cout << "回收: " << _channels[i].name() << endl;
        // }

        //解决方案二:创建时让每个管道的写端只有父进程指向
        for(auto &Channel : _channels)
        {
            Channel.Close();
            cout << "关闭: " << Channel.name() << endl;
            Channel.Wait();
            cout << "回收: " << Channel.name() << endl;
        } 
    }

    ~ChannelManage(){}
private:
    vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5;

//进程池
class ProcessPool
{
public:
    ProcessPool(int num)
        :_process_num(num)
    {
        _tm.Register(printLog);
        _tm.Register(downLoad);
        _tm.Register(upLoad);
    }

    void Work(int rfd)
    {
        while(true)
        {
            int taskcode = 0;
            ssize_t n = read(rfd, &taskcode, sizeof(taskcode));
            //父进程不写read会堵塞
            if(n > 0)
            {
                if(n != sizeof(taskcode))
                {
                    continue;
                }
                cout << "子进程[" << getpid() << "]收到:" << taskcode << endl;
                _tm.Execute(taskcode);
            }
            else if(n == 0)
            {
                cout << "子进程退出" << endl;
                break;
            }
            else
            {
                cout << "读取错误" << endl;
                break;
            }
        }
    }

    bool create()
    {
        for(int i = 0; i < _process_num; i++)
        {
            //创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if(n < 0) return false;

            //创建子进程
            pid_t subid = fork();
            if(subid < 0) return false;
            else if(subid == 0)
            {
                // //用于测试
                // cout << "第" << i+1 << "次" <<endl;
                // _cm.PrintChannel();
                // cout << "##############################" << endl;

                _cm.CloseAll(); //这里子进程会拿到父进程的之前拿到的_cm,也就是会拿到之前打开的所有写端
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                close(pipefd[0]); 
                _cm.InsertChannel(pipefd[1], subid);
            }
        }
        return true;
    }

    void Debug()
    {
        _cm.PrintChannel();
    }

    void Run()
    {
        //选择一个任务
        int taskcode = _tm.Code();

        // 负载均衡地选择一个子进程完成任务
        auto &c = _cm.Select();
        cout << "选择了一个子进程: " << c.name() << endl;

        //发送
        c.Send(taskcode);
        cout << "向子进程" << c.name() << "发送了" << taskcode << endl;
    }

    void Stop()
    {
        // //关闭父进程写端
        // _cm.StopSubProcess();
        // //回收所有子进程
        // _cm.WaitSubProcess();

        _cm.CloseAndWait();
    }

    ~ProcessPool(){}
private:
    ChannelManage _cm;
    int _process_num;
    TaskManager _tm;
};